using System.Linq;
using System.Security;
using System.Security.Permissions;
namespace Net35.Xrm.Sdk.Client
{
	[SecuritySafeCritical]
	[SecurityPermission(SecurityAction.Demand, Unrestricted = true)]
	public sealed class OnlineFederationPolicyConfiguration : OnlinePolicyConfiguration
	{
		private object _lockObject = new object();
		internal OnlineFederationPolicyConfiguration(AuthenticationPolicy xrmPolicy) : base(xrmPolicy)
		{
			if (!string.IsNullOrEmpty(PolicyHelper.GetPolicyValue(xrmPolicy, "LiveTrustLivePolicy", string.Empty)))
			{
				LiveIdentityProviderTrustConfiguration liveIdentityProviderTrustConfiguration = new LiveIdentityProviderTrustConfiguration(xrmPolicy);
				base.OnlineProviders.Add(liveIdentityProviderTrustConfiguration.Endpoint.GetServiceRoot(), liveIdentityProviderTrustConfiguration);
			}
			if (!string.IsNullOrEmpty(PolicyHelper.GetPolicyValue(xrmPolicy, "OrgIdPolicy", string.Empty)))
			{
				OrgIdentityProviderTrustConfiguration orgIdentityProviderTrustConfiguration = new OrgIdentityProviderTrustConfiguration(xrmPolicy);
				base.OnlineProviders.Add(orgIdentityProviderTrustConfiguration.Endpoint.GetServiceRoot(), orgIdentityProviderTrustConfiguration);
			}
		}
		internal void InitializeLiveTrustConfiguration(IdentityProvider identityProvider)
		{
			OrgIdentityProviderTrustConfiguration orgIdentityProviderTrustConfiguration = base.OnlineProviders.Values.OfType<OrgIdentityProviderTrustConfiguration>().FirstOrDefault<OrgIdentityProviderTrustConfiguration>();
			if (orgIdentityProviderTrustConfiguration == null)
			{
				return;
			}
			if (StringExtensions.IsNullOrWhiteSpace(orgIdentityProviderTrustConfiguration.LivePartnerIdentifier))
			{
				return;
			}
			if (base.OnlineProviders.Values.OfType<LiveIdentityProviderTrustConfiguration>().Any<LiveIdentityProviderTrustConfiguration>())
			{
				return;
			}
			lock (this._lockObject)
			{
				if (!base.OnlineProviders.Values.OfType<LiveIdentityProviderTrustConfiguration>().Any<LiveIdentityProviderTrustConfiguration>())
				{
					AuthenticationPolicy authenticationPolicy = new AuthenticationPolicy();
					authenticationPolicy.PolicyElements.Add("AppliesTo", orgIdentityProviderTrustConfiguration.LivePartnerIdentifier);
					string absoluteUri = identityProvider.ServiceUrl.AbsoluteUri;
					authenticationPolicy.PolicyElements["LiveEndpoint"] = absoluteUri;
					LiveIdentityProviderTrustConfiguration value = new LiveIdentityProviderTrustConfiguration(authenticationPolicy);
					base.OnlineProviders.Add(new System.Uri(absoluteUri), value);
				}
			}
		}
	}
}
